package com.ace.user.config;

import com.ace.user.api.interceptor.AuthorizationInterceptor;
import com.ace.user.api.interceptor.ResponseInterceptor;
import com.ace.user.config.locale.MyLocaleResolver;
import com.ace.user.util.SpringContextUtils;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

/**
 * mvc配置
 * @Author yudong
 * @Date 2018年07月03日 上午10:41
 */
@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {

    @Resource
    private ResponseInterceptor responseInterceptor;

    @Resource
    private MessageSource messageSource;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(responseInterceptor);
        addAuthorizationInterceptor(registry);
    }
    private void addAuthorizationInterceptor(InterceptorRegistry registry) {
        AuthorizationInterceptor authorizationInterceptor = SpringContextUtils.getBean(AuthorizationInterceptor.class);
        registry.addInterceptor(authorizationInterceptor).addPathPatterns("/**").excludePathPatterns("/api/v1/user/login/**").excludePathPatterns("/api/v1/user/logout/**");
    }
    /**
     * 参数校验国际化
     * @return
     */
    @Override
    public Validator getValidator() {
        return validator();
    }

    @Bean
    public Validator validator() {
        LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
        validator.setValidationMessageSource(messageSource);
        return validator;
    }

    /**
     * 配置自己的国际化语言解析器
     * @return
     */
    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResolver();
    }

    @Bean
    public AuthorizationInterceptor newAuthorizationInterceptor() {
        return new AuthorizationInterceptor();
    }
}
